package net.arogarth.aws.android.manager.views;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.manager.R;
import net.arogarth.aws.android.manager.dbmodels.AwsAccount;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

public class ImportCsv extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.import_csv);

		WebView wView = (WebView) findViewById(R.id.webDescription);
		wView.loadData(getString(R.string.aws_import_text), "text/html",
				"utf-8");
	}

	public void importCsv(View v) {

		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					// Yes button clicked
					@SuppressWarnings("unchecked")
					List<AwsAccount> accounts = (List<AwsAccount>) new AwsAccount()
							.listAll();
					for (AwsAccount account : accounts)
						account.delete();
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					break;
				}
				try {

					File intStorage = Environment.getExternalStorageDirectory();
					File importFile = new File(intStorage.getPath()
							+ "/aws_credentials.csv");

					if (importFile.exists()) {
						InputStream iStream = new FileInputStream(importFile);

						InputStreamReader inputreader = new InputStreamReader(
								iStream);
						BufferedReader buffreader = new BufferedReader(
								inputreader);

						String line;
						while ((line = buffreader.readLine()) != null) {
							String[] row = line.split(";");

							String accountName = row[0].replaceAll("^\"|\"$",
									"");
							String accessKey = row[1].replaceAll("^\"|\"$", "");
							String secretKey = row[2].replaceAll("^\"|\"$", "");

							AwsAccount account = new AwsAccount();
							account.setName(accountName);
							account.setAccessKey(accessKey);
							account.setSecretKey(secretKey);
							account.save();
						}

						iStream.close();

						Toast.makeText(getApplicationContext(), "CSV Imported",
								Toast.LENGTH_LONG).show();
						finish();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(ImportCsv.this);
		builder.setMessage("Delete current Accounts?")
				.setPositiveButton("Yes", dialogClickListener)
				.setNegativeButton("No", dialogClickListener).show();

	}
}
